/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[欢迎加盟知启蒙，一起邂逅框架梦]
 * 
 * https://www.zhiqim.com/gitcan/zhiqim/zhiqim_account.htm
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.zhiqim.account.presenter;

import org.zhiqim.account.ZacConstants;
import org.zhiqim.account.ZacSessionUser;
import org.zhiqim.account.api.pay.WxpayServer;
import org.zhiqim.account.dbo.user.UserTradeWxpay;
import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.annotation.AnIntercept;
import org.zhiqim.kernel.Global;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.kernel.extend.TreeMapSS;
import org.zhiqim.kernel.json.Jsons;
import org.zhiqim.kernel.util.Ids;
import org.zhiqim.kernel.util.Sqls;
import org.zhiqim.kernel.util.Strings;
import org.zhiqim.orm.ZTable;
import org.zhiqim.orm.dbo.Updater;

/**
 * 微信支付展示器
 * 
 * JSAPI调用的对象
 * {
 *      "appId": bridage.appId,
 *      "timeStamp": bridage.timeStamp,
 *      "nonceStr": bridage.nonceStr,
 *      "package": bridage.package,
 *      "signType": bridage.signType,
 *      "paySign": bridage.paySign 
 * },
 *
 * @version v1.0.0 @author zouzhigang 2018-4-19 新建与整理
 */
@AnAlias("WxpayPresenter")
@AnIntercept("chkZacLogin")
public class WxpayPresenter implements ZacConstants
{
    /**
     * 微信公众号支付
     * 
     * @param request       请求
     * @throws Exception    异常
     */
    public static void wxmpPay(HttpRequest request) throws Exception
    {
        WxpayServer server = Global.getService(WxpayServer.class);
        ZacSessionUser sessionUser = request.getSessionUser(ZacSessionUser.class);
        
        int tradeAmount = request.getParameterAmount2R("tradeAmount");
        String tradeSubject = request.getParameter("tradeSubject");
        String spbillCreateIp = request.getRemoteAddr();
        String tradeCallback = request.getParameter("tradeCallback");
        long tradeOrderId = request.getParameterLong("tradeOrderId", 0);
        long tradeId = Ids.longId();
        String nonceStr = Ids.uuid();
        
        //2.插入用户交易记录表
        UserTradeWxpay trade = new UserTradeWxpay();
        trade.setUserId(sessionUser.getUserId());
        trade.setTradeId(tradeId);
        trade.setTradeAmount(tradeAmount);
        trade.setTradeSubject(tradeSubject);
        trade.setTradeCallback(tradeCallback);
        trade.setTradeOrderId(tradeOrderId);
        trade.setTradeNonceStr(nonceStr);
        trade.setTradeType(WXPAY_JSAPI);
        trade.setTradeStatus(TRADE_WAITING);
        trade.setTradeCreated(Sqls.nowTimestamp());
        Global.get(ZTable.class).insert(trade);
        
        //3.接口查询
        TreeMapSS returnMap = server.unifiedorder(trade, spbillCreateIp);
        if (!server.chkSignature(returnMap))
        {
            request.setResponseError("微信支付时签名验证失败");
            return;
        }
        
        if (!"SUCCESS".equals(returnMap.get("return_code")))
        {
            request.setResponseError("微信支付时失败：" + returnMap.get("return_msg"));
            return;
        }
        
        //5.更新用户交易记录表
        Updater updater = new Updater();
        updater.addMust("tradeId", tradeId);
        updater.addField("tradeReturnDesc", Jsons.toString(returnMap));
        Global.get(ZTable.class).update(UserTradeWxpay.class, updater);
        
        //公众号支付
        TreeMapSS map = new TreeMapSS();
        map.put("appId", server.getAppId());
        map.put("timeStamp", Strings.valueOf(System.currentTimeMillis() / 1000));
        map.put("nonceStr", returnMap.get("nonce_str"));
        map.put("package", "prepay_id="+returnMap.get("prepay_id"));
        map.put("signType", "MD5");
        map.put("paySign", server.buildSignature(map));
        
        request.setResponseResult(Jsons.toString(map));
    }
    
    /**
     * 扫码支付/H5支付，定时查询微信支付状态
     * 
     * @param request       请求
     * @throws Exception    异常
     */
    public static void chkWxpayStatus(HttpRequest request)throws Exception
    {
        long tradeId = request.getParameterLong("tradeId");
        
        UserTradeWxpay wxpay = Global.get(ZTable.class).item(UserTradeWxpay.class, tradeId);
        if (wxpay == null)
        {
            request.setResponseError("用户交易记录不存在");
            return;
        }
        
        if ("SUCCESS".equals(wxpay.getTradeStatus()))
        {//成功返回701
            request.setResponseResult(701, "/account/index.htm");
        }
    }
}
